<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 复核管理详情 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="pageType != 'look' ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="复核内容"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="''" @selectOrg="selectOrg"> </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="复核结果"></title-name>
          <div v-if="pageType === 'look'">
            <section v-for="item in form.technicalReviewManagementReslutList" :key="item.id">
              <custom-form :isEmit="false" :formList="formListThree" :form="item" :editModel="''"> </custom-form>
              <hr class="hr" />
            </section>
          </div>
          <div v-else>
            <custom-form :isEmit="false" :formList="formListTwo" :form="form" :editModel="''"> </custom-form>
          </div>

          <a-col :md="24" :sm="24"> </a-col>
        </a-card>
      </a-spin>

      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button v-if="$route.query.pageType !== 'look'" class="button_right" type="primary" :loading="loadingBtn" @click="handleSubmit">提交</a-button>
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import PreView from '@/components/PreView'
import UploadList from '@/components/UploadList'
import API from '@/api/office/hazardIdentification'
import { getTechnicalReviewManagementById, approvalManagement, getTechnicalReviewMonthPlanBYDate, insertSelectiveAdd, insertSelectiveaginAgainAdd } from '@/api/technical/technicalReview'
import { getReviewCheckProjectAll, getReviewContentAll } from '@/api/technical/reviewContent'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import Moment from 'moment'
import { setTimeout } from 'timers'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: { PreView, UploadList, SelectPersonByProject },
  data() {
    return {
      // 加载控件
      loading: false,
      // 按钮加载
      loadingBtn: false,
      // 页面类型
      pageType: '',
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      // 表单
      form: { fileInfoList: [], checkAreaId: undefined, checkContentId: undefined, practicalParticipantName: [] },
      // form: { viewName: '', fileInfoList: [] }, // 表单
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      id: '',
      schemArr: [], //方案名称
      checkProjectArr: [], //项目名称
      checkContentArr: [], //复核内容数组
      checkAreatArr: [], //复核区域数组
      checkPositionArr: [], //复核部位数组
      projectIdData: '',
      reviewTypeData: {}, //计划内数据
      rules: {
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        reviewType: [{ required: true, message: '请选择', trigger: 'change' }],
        // constructionProgramId: [{ required: true, message: '请选择', trigger: 'change' }],
        checkProjectId: [{ required: true, message: '请选择', trigger: 'change' }],
        checkContentId: [{ required: true, message: '请选择', trigger: 'change' }],
        reviewConclusion: [{ required: true, message: '请选择', trigger: 'change' }],
        practicalOrganizerId: [{ required: true, message: '请选择', trigger: 'change' }],
        practicalChargePersonId: [{ required: true, message: '请选择', trigger: 'change' }],
        reviewCompletionTime: [{ required: true, message: '请选择', trigger: 'change' }],
        reviewContent: [{ required: true, message: '请选择', trigger: 'change' }],
        checkAreaId: [{ required: true, message: '请选择', trigger: 'change' }],
        reviewRecord: [{ required: true, message: '请输入填报记录', trigger: 'blur' }],
        fileInfoList: [{ required: true, type: 'array', message: '请上传图片', trigger: 'blur' }],
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.acceptanceDailyRecords || []
          })
        })
      }
    }
  },
  computed: {
    formList() {
      let newFormList = [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          checkStrictly: true,
          isAutoSelectFirst: true,
          span: 16,
          disabled: this.pageType !== 'add',
          isNeedAuth: true
        },
        // /api/cscec-project-business/projects/employees/list
        {
          keyName: 'reviewType',
          type: 'a-select',
          label: '复核类型',
          disabled: this.pageType !== 'add',
          data: [
            {
              label: '计划内',
              value: 0
            },
            {
              label: '计划外',
              value: 1
            }
          ],
          change: () => {
            this.getPlanInfo()
          }
        },
        {
          keyName: 'constructionProgramId',
          type: 'a-select',
          disabled: this.pageType !== 'add',
          label: '方案名称',
          data: this.schemArr
        },
        {
          keyName: 'checkProjectId',
          type: 'a-select',
          disabled: this.pageType !== 'add',
          label: '复核项目',
          data: this.checkProjectArr,
          change: (e) => {
            this.checkProjectChange(e)
          }
        },
        {
          keyName: 'checkContentId',
          type: 'a-select',
          disabled: this.pageType !== 'add' || this.form.reviewType !== 1,
          label: '复核内容',
          data: this.checkContentArr
        },
        {
          keyName: 'checkAreaId',
          type: 'a-tree-Select',
          disabled: this.pageType !== 'add' || this.form.reviewType !== 1,
          label: '复核区域',
          multiple: true,
          data: this.checkAreatArr
        },
        {
          keyName: 'checkParts',
          type: 'BaseInput',
          disabled: this.pageType !== 'add' || this.form.reviewType !== 1,
          label: '复核部位',
          span: 8
        },
        { keyName: 'organizerName', hidden: this.form.reviewType == 1, type: 'BaseInput', label: '组织人', disabled: true, span: 8 },
        { keyName: 'chargePersonName', hidden: this.form.reviewType == 1, type: 'BaseInput', label: '责任人', disabled: true, span: 8 },
        { keyName: 'plannedCompletionTime', hidden: this.form.reviewType == 1, type: 'BaseInput', label: '计划完成时间', disabled: true, span: 8 }
      ]
      // if (this.typeReview * 1 === 1) {
      //   newFormList.splice(4)
      // } else if (this.typeReview * 1 === 2) {
      //   newFormList.splice(3)
      // }
      return newFormList
    },
    formListTwo() {
      let newFormListTwo = [
        // { keyName: 'checkParts', type: 'BaseInput', label: '复核部位', disabled: true, span: 8 },
        // { keyName: 'reviewConclusionName', type: 'BaseInput', label: '复核结论', disabled: true, span: 8 },
        {
          keyName: 'reviewConclusion',
          disabled: this.pageType === 'look',
          type: 'a-select',
          label: '复核结论',
          data: [
            {
              label: '通过',
              value: 0
            },
            {
              label: '不通过',
              value: 1
            }
          ]
        },
        {
          keyName: 'practicalOrganizerId',
          viewName: 'practicalOrganizerName',
          type: SelectPersonByProject,
          disabled: this.pageType === 'look',
          label: '实际组织人',
          attrs: {
            addJob: false,
            id: this.form.branchCompanyId,
            projectId: this.form.projectId,
            showSearch: true,
            isProject: true
          },
          personChanged: (e) => {
            this.form.practicalOrganizerName = e.employeeName;
          }
        },
        {
          keyName: 'practicalParticipantId',
          viewName: 'practicalParticipantName',
          disabled: this.pageType === 'look',
          type: SelectPersonByProject,
          label: '参与复核人',
          attrs: {
            addJob: false,
            id: this.form.branchCompanyId,
            projectId: this.form.projectId,
            showSearch: true,
            isProject: true,
            mode: 'multiple',
            maxTagCount: 100
          },
          personChanged: (e) => {
            this.form.practicalParticipantName = []
            if (Array.isArray(e)) {
              e.forEach((item) => {
                this.form.practicalParticipantName.push(item.employeeName);
              })
            }
          }
        },
        {
          keyName: 'practicalChargePersonId',
          viewName: 'practicalChargePersonName',
          disabled: this.pageType === 'look',
          type: SelectPersonByProject,
          label: '实际责任人',
          attrs: {
            addPhone: false,
            id: this.form.branchCompanyId,
            projectId: this.form.projectId,
            showSearch: true,
            isProject: true
          },
          personChanged: (e) => {
            this.form.practicalChargePersonName = e.employeeName;
          }
        },
        {
          keyName: 'reviewCompletionTime',
          type: 'a-date-picker',
          disabled: this.pageType === 'look',
          placeholder: '请选择日期',
          label: '复核完成时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          label: '填报时间',
          keyName: 'fillTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '填报人',
          keyName: 'informantName',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'reviewRecord',
          type: 'BaseTextarea',
          label: '复核记录',
          attrs: {
              maxLength : 1000,
            },
          span: 22
        },
        {
          keyName: 'fileInfoList',
          disabled: this.pageType === 'look',
          hidden: false,
          label: '图片上传',
          businessCode: 'QM01',
          span: 24,
          attrs: {
            uploadType: 'image',
            editModel: this.pageType === 'look' ? '0' : '1'
          },
          type: 'uploadFile'
        }
      ]
      return newFormListTwo
    },
    formListThree(){
      return [
        {
          label: '复核结论',
          keyName: 'reviewConclusionName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '实际组织人',
          keyName: 'practicalOrganizerName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '参与复核人',
          keyName: 'practicalParticipantName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '实际责任人',
          keyName: 'practicalChargePersonName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '复核完成时间',
          keyName: 'reviewCompletionTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '填报时间',
          keyName: 'fillTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '填报人',
          keyName: 'informantName',
          type: 'BaseInput',
          disabled: true
        },
        {
          keyName: 'reviewRecord',
          type: 'BaseTextarea',
          label: '复核记录',
          disabled: true,
          attrs: {
              maxLength : 1000,
            },
          span: 22
        },
        {
          keyName: 'fileInfoList',
          disabled: true,
          hidden: false,
          label: '图片上传',
          businessCode: 'QM01',
          span: 24,
          attrs: {
            uploadType: 'image',
            editModel: '0'
          },
          type: 'uploadFile'
        }
      ]
    }
  },
  created() {
    this.pageType = this.$route.query.pageType
  },
  mounted() {
    this.getReviewContent()
    this.getDetails()

  },
  methods: {
    /**
     * @description: 获取复合区域
     * @param {projectId 项目id}
     * @return {res.data}
     */
    async getCheckArea() {
      if (!this.form.projectId) return
      let res = await API.subPackArea({}, { id: this.form.projectId, sources: 0 })
      if (res.code === this.SUCCESS_CODE) {
        if (!res.data[0].children) {
          this.checkAreatArr = []
          return false
        }
        this.checkAreatArr = this.filterLeaderTree(res.data)
        this.$forceUpdate()
      }
    },
    /**
     * @description: 过滤复合区域
     * @param {projectId 项目id}
     * @return {res.data}
     */
    filterLeaderTree(treeData) {
      return treeData.map((item) => {
        if (item.children && item.children.length) {
          return {
            ...item,
            disabled: true,
            children: this.filterLeaderTree(item.children)
          }
        } else {
          return {
            ...item
          }
        }
      })
    },
    /**
     * @description: 根据项目改变带出信息
     * @param {projectId 项目id}
     * @return {res.data}
     */
    async checkProjectChange(e) {
      let checkProjectData = {}
      this.checkProjectArr.forEach((item) => {
        if (item.id === e) {
          checkProjectData = item
        }
      })
      let contentParams = { checkId: checkProjectData.checkProjectId, status: true }
      if (this.form.reviewType === 1) {
        contentParams.checkId = checkProjectData.id
        this.form.reviewContentId = ""
      }else {
        this.form.reviewContentId = checkProjectData.id
      }
      /***************************************获取复合内容  **********************************/

      let res = await getReviewContentAll(contentParams)
      if (res.data) {
        this.checkContentArr = res.data.map((item) => {
          item.label = item.content
          item.value = item.id
          return item
        })
      }
      /***************************************获取复合内容  **********************************/

      /***************************************计划内带出数据  **********************************/
      if (this.form.reviewType === 0 && this.pageType === 'add') {
        let month = new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
        let param = { projectId: this.form.projectId, month }
        let response = await getTechnicalReviewMonthPlanBYDate(param)
        if (response.data?.length > 0) {
          let data = response.data.filter((item) => {
            return item.id === checkProjectData.id
          })
          if (data[0]){
            this.reviewTypeData = data[0]
          }
          let arr = ['checkContentId', 'checkAreaId', 'checkParts', 'organizerName', 'chargePersonName', 'plannedCompletionTime']
          arr.forEach((item) => {
            this.$set(this.form, item, data[0][item])
          })

          if (this.form.checkAreaId) {
            this.form.checkAreaId = data[0].checkAreaId.split(',')
          } else {
            this.form.checkAreaId = undefined
          }
          let chargePersonId = []
          let chargePersonName = []
          data[0].technicalReviewMonthPlanCharges.forEach((item) => {
            chargePersonName.push(item.chargePersonNamePhone)
            chargePersonId.push(item.chargePerson)
          })
          this.$set(this.form, 'chargePersonId', chargePersonId.join(','))
          this.$set(this.form, 'chargePersonName', chargePersonName.join(','))
        }
        /***************************************计划内带出数据  **********************************/
      }
    },
    /**
     * @description: 复核类型为计划内 根据项目自动带出
     * @param {projectId 项目id}
     * @return {res.data}
     */
    async getPlanInfo() {
      //清空表单数据
      let arr = ['checkProjectId', 'checkContentId', 'checkAreaId', 'checkParts', 'organizerName', 'chargePersonName', 'plannedCompletionTime']
      arr.forEach((item) => {
        this.$set(this.form, item, '')
      })
      this.form.checkAreaId = undefined
      let month = new Date().getFullYear() + '-' + (new Date().getMonth() + 1)
      let param = { projectId: this.form.projectId, month }
      if (this.form.reviewType === 0) {
        let res = await getTechnicalReviewMonthPlanBYDate(param)
        this.checkProjectArr = res.data.map((item) => {
          item.label = item.checkProjectName
          item.value = item.id
          return item
        })
      } else {
        this.getReviewContent()
      }
    },
    /**
     * @description: 获取方案名称
     * @param {projectId 项目id}
     * @return {res.data}
     */
    async getschemArr() {
      let param = { projectId: this.form.projectId }
      let res = await approvalManagement(param)
      if (res.code === 200 && res.data?.length > 0) {
        this.schemArr = res.data.map((item) => {
          item.label = item.name
          item.value = item.id
          return item
        })
      }
    },
    /**
     * @description: 获取复核项目
     * @param status  状态
     * @return {res.data}
     */
    async getReviewContent() {
      let params = { status: true }
      let res = await getReviewCheckProjectAll(params)
      if (res.data?.length > 0) {
        this.checkProjectArr = res.data.map((item) => {
          item.label = item.name
          item.value = item.id
          return item
        })
      }
    },
    /**
     * @description: 所属单位
     * @param
     * @return {}
     */
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
        if (this.pageType === 'add') {
          this.form.checkAreaId = undefined
        } else {
          this.form.projectId = this.projectIdData
        }
        this.getschemArr()
        this.getCheckArea()
        this.$forceUpdate()
      }
    },
    /**
     * @description: 提交表单
     * @param {this.form}
     * @return {}
     */
    handleSubmit() {
      this.loadingBtn = true
      setTimeout(() => {
        this.loadingBtn = false
      }, 3000)
      // 校验表单
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let params = { ...this.form }
          if (Array.isArray(params.practicalParticipantId)) {
            params.practicalParticipantId = params.practicalParticipantId.join(',')
          } else {
            delete params.practicalParticipantId
          }
          if (Array.isArray(params.checkAreaId)) {
            params.checkAreaId = params.checkAreaId.join(',')
          }
          if (Array.isArray(params.practicalParticipantName)) {
            params.practicalParticipantName = params.practicalParticipantName.join(',')
          }
         
          if (this.form.reviewType === 0) {
            params.checkProjectId = this.reviewTypeData.checkProjectId ? this.reviewTypeData.checkProjectId:params.checkProjectId
          }
          const user = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
          params.creatorName = user.name
          params.informantId = user.id
          let res = ''
          if (this.pageType === 'add') {
            res = await insertSelectiveAdd(params)
          } else {
            params.reviewManagementId = params.id
            res = await insertSelectiveaginAgainAdd(params)
          }
          if (res?.data) {
            this.loadingBtn = false
            this.$message.success('新增成功')
            this.handleClose()
          } else {
            this.loadingBtn = false
          }
        } else {
          this.loadingBtn = false
          this.$message.warning('请填写完所有必填项信息')
        }
      })
    },
    /**
     * @description: 关闭页面
     * @param
     * @return
     */
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    },
    /**
     * @description: 获取详情
     * @param
     * @return {}
     */
    getDetails() {
      const user = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      this.form.informantName = user.name
      this.form.fillTime = Moment(new Date()).format('YYYY-MM-DD')
      if (!this.id) return
      this.loading = true

      getTechnicalReviewManagementById({ id: this.id })
        .then((res) => {
          if (res.data) {
            this.loading = false

            // if (res.data.practicalParticipantId) {
            //   res.data.practicalParticipantId = res.data.practicalParticipantId.split(',') || ''
            // }
            if (res.data.checkAreaId) {
              res.data.checkAreaId = res.data.checkAreaId.split(',') || ''
            }
            this.form = { ...this.form, ...res.data }

            this.projectIdData = res.data.projectId
            this.getCheckArea()
            this.checkProjectChange(this.form.checkProjectId)
            /* *********************处理重新复核数据 *************************/
            if (this.pageType === 'edit') {
              delete this.form.technicalReviewManagementReslutList
              let arr = ['reviewConclusion', 'practicalOrganizerId', 'practicalParticipantId', 'practicalParticipantName', 'practicalChargePersonId', 'reviewCompletionTime']
              arr.forEach((item) => {
                this.$set(this.form, item, undefined)
              })
              this.form.fillTime = Moment(new Date()).format('YYYY-MM-DD');
              this.form.informantName = user.name
            }
            /* *********************处理重新复核数据 *************************/
            /* *********************处理查看数据 *************************/
            if (this.pageType === 'look') {
              res.data.technicalReviewManagementReslutList.forEach((item) => {
                if (item.practicalParticipantId) {
                  item.practicalParticipantId = item.practicalParticipantId.split(',')
                }
              })
              this.$set(this.form, 'technicalReviewManagementReslutList', res.data.technicalReviewManagementReslutList)
            }
            /* *********************处理查看数据 *************************/
            this.$refs.table.loadData()
          }
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
}
.fileInfoList-tip {
  position: absolute;
  z-index: 1000;
  left: -109px;
  top: -3px;
  color: red;
}
.hr {
  background: #f5f5f5;
  height: 10px;
  border: none;
}
</style>
